package mspbots.tsheets.data.core.synclogs;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.tsheets.common.ResultSync;
import mspbots.tsheets.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * mspbots.data.sync.autotask.tickets.AtTicketsReceiver
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/17
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class SyncLogsReceiver extends AbstractToolsUtil {

    private final SyncLogsRepository syncLogsRepository;

    @RabbitListener(queues = "tsheets.logs.task.sync")
    public void processMessage(ResultSync content) {

        SyncLogs syncLogs = SyncLogs.builder().build();
        BeanUtils.copyProperties(content, syncLogs);
        syncLogs.setMsg(ObjectUtils.getDisplayString(content.getMsg()));
        syncLogs.setParams(super.objectMapper.convertValue(content.getParams(), JsonNode.class));
        syncLogs.setStatus(content.getStatus().value());
        Mono.just(syncLogs).flatMap(this.syncLogsRepository::save).block(Duration.ofSeconds(10));
    }

}
